package br.com.fidalgotecnologia.seguranca.listener;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthorizationListener implements PhaseListener {  
	  
    

	@Override
	public void afterPhase(PhaseEvent event) {  
        FacesContext fc = event.getFacesContext();  
        ExternalContext ec = fc.getExternalContext();  
        HttpServletResponse response = (HttpServletResponse) ec.getResponse();  
          
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);  
        
        String usuarioLogado = (String) session.getAttribute("UsuarioLogado");  
        
        String currentPage = fc.getViewRoot().getViewId();  
        
        if (usuarioLogado == null) {  
            try {  
                FacesContext.getCurrentInstance().getExternalContext().redirect("/");  
            } catch (IOException ex) {  
                Logger.getLogger(AuthorizationListener.class.getName()).log(Level.SEVERE, null, ex);  
  
            }  
        }  
        if (currentPage.contains("login") && usuarioLogado != null) {  
            try {  
                FacesContext.getCurrentInstance().getExternalContext().redirect("/restrito/");  
            } catch (IOException ex) {  
                Logger.getLogger(AuthorizationListener.class.getName()).log(Level.SEVERE, null, ex);  
            }  
        }  
  
  
        response.setHeader("Expires", "-1");  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidade, proxy-revalidade, private, post-check=0, pre-check=0");  
        response.setHeader("Pragma", "no-cache");  
    }

	@Override
	public void beforePhase(PhaseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public PhaseId getPhaseId() {
		// TODO Auto-generated method stub
		return null;
	}  
}
